You mount a volume to a container using the -v or --mount flags with the docker run command, specifying which volume to mount and where to mount it inside the container.
Mounting a volume to a container makes the persistent data stored in the volume available at a specific path inside the container. Docker provides two syntax options for mounting volumes: the simpler -v (or --volume) flag, and the more explicit --mount flag. Both achieve the same result, but --mount is recommended for production environments because it's more verbose and less prone to errors.
The -v flag uses a compact format: -v volume-name:container-path:options where options like ro (read-only) can be added .
The --mount flag uses explicit key-value pairs separated by commas: --mount type=volume,source=myvol,target=/app,readonly .
If the specified volume doesn't exist, Docker automatically creates it for both syntaxes .
You can mount the same volume to multiple containers, enabling data sharing between them .
The container path must be an absolute path, and Docker will create the directory if it doesn't exist .
After mounting, any data written to the container's mount path is actually stored in the volume and persists even after the container is removed. You can verify the mount worked by inspecting the container with docker inspect and looking at the Mounts section, which shows the source volume, destination path, and mount options. For MySQL or PostgreSQL containers, this pattern is essential because it ensures database files survive container updates or crashes.